import router from "./router";
import store from "./store";
import { getCookie } from "@/utils/auth"; // get token from cookie
import { isWPF, sendWebView2, generateRandomUUID } from "./utils/webview2.js";
import { isQtClient, generateRandomUUID as generateRandomUUIDQT, receive } from './utils/qwebUtil.js'
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
// import { Message } from 'element-ui'
const _import = path => import(`@/modules/index/views/${path}.vue`);

var webName = getCookie("website_name") || "轻量化诊断预测算法生成系统";
document.title = webName;
var website_name = document.getElementById("website_name");
website_name = webName;
store.commit("SET_WEB_NAME", website_name);

//will change
// var userinfo = {name:getCookie("creater")||"zengjw5"};
// console.log('_username', getCookie('_username'));
var userinfo = { name: getCookie("_username") || "test" };
// console.log(userinfo)
// var token =getCookie("token")||"zengjw5zengjw5zengjw5zengjw5zengjw5";
store.commit("SET_USER_NAME", userinfo.name);
// store.commit("SET_TOKEN", token);


let res = {};
if (isQtClient) {
    const uuid = generateRandomUUIDQT();
    let sendObject;
    /* eslint-disable-next-line */
    const channel = new QWebChannel(
        window.qt.webChannelTransport,
        async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
                RequestUrl: `/user/search-by-username?userName=${userinfo.name}`,
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {  },
                isStringParam: false,
                requestId: uuid,
            };
            await send();
            await receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
        }
    );
    /* eslint-disable-next-line */
    async function send() {
        sendObject.sendMessage.connect(function (data) {
            if (!data) {
                console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
                const data =
                    result.data && result.data.length ? result.data[0] : null;
                // console.log(data, "username");
                if (data) {
                    store.commit("SET_USER", data);
                }
            }
        });
    }
} else if (isWPF) {
    const uuid = generateRandomUUID();
    sendWebView2(
        `/user/search-by-username?userName=${userinfo.name}`,
        "get",
        "application/json;charset=UTF-8",
        {
        },
        false,
        uuid
    );
    window.chrome.webview.addEventListener("message", e => {
        let res = e.data;
        let result = res.response;
        if (result.success && res.webInfo.requestId === uuid) {
            // console.log(result);
            const data =
                result.data && result.data.length ? result.data[0] : null;
            // console.log(data, "username");
            if (data) {
                store.commit("SET_USER", data);
            }
        }
    });
} else {
    store
        .dispatch("userSearchByUsername", {
            userName: userinfo.name
        })
        .then(res => {
            // const result = res[0].data || {};
            const result = res.data || {};
            if (result.success) {
                const data =
                    result.data && result.data.length ? result.data[0] : null;
                // console.log(data, "username");
                if (data) {
                    store.commit("SET_USER", data);
                }
            }
        });
}


// let token=window.sessionStorage.getItem("token");
// router.beforeEach((to, from, next) => {
//     let token = store.getters.GET_TOKEN
//     let hasRoutes = store.state.hasRoutes
//     let menuList = store.getters.GET_MENULIST;
//     const whiteList = ['/login'] // 白名单
//     if (token) {
//         if (!hasRoutes) {
//             bindRoute(menuList);
//             store.commit("SET_ROUTES_STATE", true)
//         }
//         next()

//     } else {
//         if (whiteList.includes(to.path)) {
//             next()
//         } else {
//             next('/login')
//         }
//     }
// })


const bindRoute = (menuList) => {
    let newRoutes = router.options.dinamicRoutes;
    menuList.forEach(menu => {
        if (menu.children) {
            menu.children.forEach(m => {
                // 菜单转成路由
                let route = menuToRoute(m, menu.name);
                console.log(route);
                if (route) {
                    newRoutes[1].children.push(route); // 添加到路由管理
                }
            })
        }
    })
    // 重新添加到路由
    // newRoutes.forEach(route => {
    //     console.log(route);
    //     router.addRoute(route);
    // })
    router.addRoutes(newRoutes);
}

// // 菜单转成路由
const menuToRoute = (menu, parentName) => {

    if (!menu.component) {
        return null
    } else {
        let route = {
            name: menu.name,
            path: menu.path,
            meta: {
                parentName: parentName
            }
        }
        route.component = () => _import(menu.component)

        return route
    }
}